import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { Student, StudentQuery } from '../types/student';
import { StudentService } from '../services/student.service';
import { StudentFormComponent } from '../student-form/student-form.component';

@Component({
  selector: 'app-student',
  imports: [
    CommonModule,
    FormsModule,
    MatTableModule,
    MatPaginatorModule,
    MatInputModule,
    MatFormFieldModule,
    MatButtonModule,
    MatIconModule,
    MatDialogModule,
    MatSnackBarModule
  ],
  templateUrl: './student.component.html',
  styleUrl: './student.component.scss'
})
export class StudentComponent implements OnInit {

  constructor(
    private studentService: StudentService,
    private dialog: MatDialog,
  ) {}

  stuColumns: string[] = [
    'student_id',
    'name',
    'age',
    'class',
    'gender',
    'phone',
    'email',
    'address',
    'actions',
  ]

  dataSource: Student[] = []
  classFilter: string = ''
  pageSize: number = 10
  pageNumber: number = 1
  pageIndex: number = 0
  total: number = 0


  loadStudents() {
    // console.log('xxxx');
    const query: StudentQuery = {
      page: this.pageNumber,
      page_size: this.pageSize,
      class: this.classFilter
    }
    this.studentService.getStudents(query).subscribe({
      next:(resp)=> {
        this.dataSource = resp.data.students
        console.log(this.dataSource);
        
        this.total = resp.data.total
      },
      error:()=>{

      }
    })
  }

  openDialog() {
    const dialogRef = this.dialog.open(StudentFormComponent, {
      width: '400px'
    })
    dialogRef.afterClosed().subscribe({
      next:(val)=> {
        if (val) {
          this.loadStudents()
        }
      }
    })
  }


  ngOnInit(): void {
    this.loadStudents()  
  }
}
